package benchmark.clients;

import java.io.IOException;
import java.io.StringReader;
import java.util.Date;

import javax.xml.bind.JAXBException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.log4j.Logger;

import com.sun.jersey.api.json.JSONJAXBContext;
import com.sun.jersey.api.json.JSONUnmarshaller;

import domainspecific.types.*;

import benchmark.Client;

public class RestClient implements Client {
	private static Logger logger = Logger.getLogger(RestClient.class);
	
	private static Logger restlogger = Logger.getLogger("restlogger");
	
	private String baseUri;
	private String requestPath;
	private static HttpClient defaultHttpClient;
	private JSONJAXBContext ctx;
	private JSONUnmarshaller unmarshal;
	private MeterReadings m;
	
	static{
		 ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
	     cm.setMaxTotal(100);

	     defaultHttpClient = new DefaultHttpClient(cm);
	}
	
	public RestClient(){
	
		String host = "localhost";
		String port = "9998";
		
		if(System.getenv().containsKey("READINGS_HOST")){
			host = System.getenv().get("READINGS_HOST");
		}
		
		if(System.getenv().containsKey("READINGS_PORT")){
			port = System.getenv().get("READINGS_PORT");
		}
		
		baseUri = "http://" + host + ":" + port + "/";
		
		if(System.getenv().containsKey("BaseUri")){
			baseUri = System.getenv("BaseUri");
		}
		
		requestPath = "meterreadings/meter/";
		
		if(System.getenv().containsKey("requestPath")){
			requestPath = System.getenv("requestPath");
		}	
		
		System.out.println("Initialising unmarshaller...");
		try {
			ctx = new JSONJAXBContext(domainspecific.types.MeterReadings.class);
			unmarshal = ctx.createJSONUnmarshaller();
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Got an unmarshaller.");
	}
	
	static private long numReadings = 0;
    static private String interval = "MINUTE";
    static
    {
    	if(System.getenv().containsKey("READINGS_NUMREADINGS")){
			numReadings = Long.parseLong(System.getenv().get("READINGS_NUMREADINGS"));
		}
    	if(System.getenv().containsKey("READINGS_INTERVAL")){
			interval = System.getenv().get("READINGS_INTERVAL");
		}
    }
    
	public void sendRequest() {
	
		StringBuilder sendPath = new StringBuilder(requestPath + "" + ((int) ( Math.random() * 100000))); // random meter id
		sendPath.append('/');
		// 1 day, 15 minute interval
		long tFrom=(int)(Math.random()*(java.lang.System.currentTimeMillis()/1000));
		sendPath.append(tFrom);
		sendPath.append('/');
		sendPath.append(numReadings);
		sendPath.append('/');
		sendPath.append(Interval.valueOf(interval));
		HttpGet httpget = new HttpGet(
	     baseUri + sendPath.toString());	
		httpget.setHeader("accept", "application/json");
		try {
			
			logger.info(baseUri + sendPath);
			long begin = System.currentTimeMillis();
//			defaultHttpClient.execute(httpget);
			// Create a response handler
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = defaultHttpClient.execute(httpget, responseHandler);
            
            System.out.println("----------------------------------------");
            if(null!=this.unmarshal)
				try {
					m = unmarshal.unmarshalFromJSON(new StringReader(responseBody), domainspecific.types.MeterReadings.class);
					System.out.println(m.getReadings().size());
				} catch (JAXBException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            System.out.println("----------------------------------------");
            long finished = System.currentTimeMillis();
//			HttpEntity entity = response.getEntity();
//			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
//			// debug
//			String line;
//			while( (line = reader.readLine()) != null){
//				System.out.println(line);
//			}					
			long responseTime = (finished - begin);
			restlogger.info("" + responseTime);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

}
